struct Formula
    product
    productNum
    material
    materialNum
    cost
    function Formula(product, productNum, material, materialNum, cost)
        new(product, productNum, material, materialNum, cost)
    end
end

"""
subformula = queryproduct(item, formula)
查询产物中包含 item 的配方
"""
function queryproduct(item, formula)
    global ind = []
    for i = 1:length(formula)
        if Bool(sum( item .== formula[i].product ))
            ind = [ind; i]
        end
    end
    print(ind)
    qform = formula[ind]
    return qform
end

"""
subformula = querymaterial(item, formula)
查询原料中包含 item 的配方
"""
function querymaterial(item, formula)
    global ind = []
    for i = 1:length(formula)
        if Bool(sum( item.== formula[i].material ))
            ind = [ind; i]
        end
    end
    qform = formula[ind]
    return qform
end

"""
queryproducepath(item, num, formulas, fileID, indent)
查询某一产物的合成路径和每个原料的生产率
item    待查询产物
num     产物的目标产率
formulas配方列表
fileID  指定输出的位置。stdout为终端，输出到文件需要事先打开
indent  缩进符
"""
function queryproducepath(item, num, formulas, fileID; indent="", indentadd="   |")
    formula=queryproduct(item, formulas)
    print(fileID, "$indent$item,$num\n")
    if length(formula) > 1
        return
    else
        x = formula[1]
        if isempty(x.material[1])
            return
        else
            for i=1:length(x.material)
                queryproducepath( x.material[i],
                    num//x.productNum[1]*x.materialNum[i],
                    formulas, fileID, indent = indent*indentadd, indentadd = indentadd)
            end
        end
    end
end

function str2double(s)
    t = []
    for i=1:length(s)
        tt = parse(Float64, s[i])
        tt = Rational{Int32}(tt)
        t = [t; tt]
    end
    return t
end

"""
formula = loadformula()
加载配方数据，返回配方结构体数组
"""
function loadformula()
    filename="formula_cn.txt"
    f = open(filename, "r")
    lines = readlines(f)
    close(f)
    formula = []
    for i=1:length(lines)
        line = lines[i]
        if line[1]=='#'
            continue
        else
            part = split(line,";",keepempty=true)
            item = split(part[1],",",keepempty=true)
            product = item[1:2:end]
            productNum = str2double(item[2:2:end])
            if isempty(part[2])
                material = [""]
                materialNum = [""]
            else
                s = split(part[2],',')
                material = s[1:2:end]
                materialNum = str2double(s[2:2:end])
            end
            cost = part[3]
            if !isempty(cost)
                if cost[end]=='s'
                    cost = parse(Float64, cost[1:end-1])
                end
            end
            formulaUnit = Formula(product, productNum, material, materialNum, cost)
            formula = [ formula;formulaUnit ]
        end
    end
    return formula
end
